<?php
if (!defined('ABSPATH')) {
    exit();
}

function get_ajax_data_react(){
    require_once CMC_PATH . 'includes/db/cmc-coins-db.php';
    require_once CMC_PATH . 'includes/cmc-functions.php';
    
    // Initialize the database and variables
    $cmcDB = new CMC_Coins();
    $coins_list = array();
    $order_col_name = 'market_cap';
    $order_type = 'DESC';

    // Fetch and validate parameters from the request with strict input validation
    $start_point = 0;
    $number = 100; // Default batch size is 100
    $cat = '';
    $search = '';
    $fav_coins = 'NA';

    // Validate and sanitize offset parameter
    if (isset($_GET['offset']) && is_numeric($_GET['offset'])) {
        $start_point = max(0, intval($_GET['offset']));
    }

    // Validate and sanitize number parameter with reasonable limits
    if (isset($_GET['number']) && is_numeric($_GET['number'])) {
        $number = max(1, min(1000, intval($_GET['number']))); // Limit between 1 and 1000
    }

    // Validate and sanitize category parameter
    if (isset($_GET['category']) && is_string($_GET['category'])) {
        $cat = sanitize_text_field($_GET['category']);
        // Additional validation for category - only allow alphanumeric, hyphens, and underscores
        if (!preg_match('/^[a-zA-Z0-9\-\_]+$/', $cat)) {
            $cat = '';
        }
    }

    // Validate and sanitize search parameter
    if (isset($_GET['search']) && is_string($_GET['search'])) {
        $search = sanitize_text_field($_GET['search']);
        // Limit search length to prevent abuse
        if (strlen($search) > 100) {
            $search = substr($search, 0, 100);
        }
        $search = strtoupper($search);
    }

    // Validate and sanitize coinID parameter
    if (isset($_GET['coinID']) && is_string($_GET['coinID'])) {
        $fav_coins = sanitize_text_field($_GET['coinID']);
        // Additional validation for coinID - only allow alphanumeric and commas
        if (!preg_match('/^[a-zA-Z0-9,\s]+$/', $fav_coins)) {
            $fav_coins = 'NA';
        }
    }

    // Fetch the total count of rows in the database
    $total_count = $cmcDB->get_coins([], null, true); // Pass `$count` as true to get the total count
    
    // Adjust API data request based on start point
    if($start_point > 2599){
        CMC_api_data::cmc_get_selected_api_data(13);
    }
    elseif($start_point > 2299){
        CMC_api_data::cmc_get_selected_api_data(12);
    }
    elseif($start_point > 2099) {
        CMC_api_data::cmc_get_selected_api_data(11);
    }
    elseif($start_point > 1899) {
        CMC_api_data::cmc_get_selected_api_data(10);
    }
    elseif($start_point > 1699) {
        CMC_api_data::cmc_get_selected_api_data(10);
    }
    elseif($start_point > 1499) {
        CMC_api_data::cmc_get_selected_api_data(9);
    }
    elseif($start_point > 1299) {
        CMC_api_data::cmc_get_selected_api_data(8);
    }
    elseif($start_point > 1099) {
        CMC_api_data::cmc_get_selected_api_data(7);
    }
    elseif($start_point > 899) {
        CMC_api_data::cmc_get_selected_api_data(6);
    }
    elseif($start_point > 699) {
        CMC_api_data::cmc_get_selected_api_data(5);
    }
    elseif($start_point > 399) {
        CMC_api_data::cmc_get_selected_api_data(4);
    }
    elseif($start_point > 299) {
        CMC_api_data::cmc_get_selected_api_data(3);
    }
    elseif($start_point > 99) {
        CMC_api_data::cmc_get_selected_api_data(2);
    }
    
    // Prepare arguments for the query based on the parameters
    $args = [
        'number' => $number,
        'offset' => $start_point,
        'coin_category' => $cat,
        'coin_search' => $search,
        'orderby' => $order_col_name,  // Use the order column
        'order' => $order_type,        // Use the order type
    ];
    
    if ($fav_coins !== 'NA') {
        $args['coin_id'] = $fav_coins;
    }

    // Fetch the coins from the database
    $coins = $cmcDB->get_coins($args);
    // Process coin logos
    $coin_ids = array_column($coins, 'coin_id');
    $coin_logos = array_map(function ($coin_id) {
        return coin_list_logo($coin_id, 32);
    }, $coin_ids);
    
    // Combine coin data with logos and additional details
    $combined_data = [];
    foreach ($coins as $key => $coin) {
        $coin_array = (array)$coin;

        $stable_coin_cate = false;
        $cate = isset($coin_array['coin_category']) ? unserialize($coin_array['coin_category']) : '';
    
        if (is_array($cate) && in_array('stable-coin', $cate)) {
            $stable_coin_cate = true;
        }
    
        $coin_array['logo'] = $coin_logos[$key];
        $coin_array['stable_coin_cate'] = $stable_coin_cate;
        $coin_array['weekly_chart'] = isset($coin_array['weekly_price_data']) && !empty($coin_array['weekly_price_data']) ? json_encode(unserialize($coin_array['weekly_price_data'])) : 'false';
        
        // Remove weekly_price_data from the array
        unset($coin_array['weekly_price_data']);
    
        $combined_data[] = $coin_array;
    }

    // Return the data with the total count
    return [
        'total_count' => $total_count,
        'data' => $combined_data,
    ];
}
?>
